package boundarys;

import java.awt.Font;
import java.awt.Panel;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import common.CheckBoxJList;
import common.CheckBoxObject;
import controllers.MaintainingResidentialAreaController;
import controllers.ManageTypesController;
import controllers.SetMarketingPattersController;
import entitys.Area;
import entitys.Category;
import entitys.Product;
import entitys.Reply;
import entitys.Type;
import enums.Command;
import enums.Result;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

public class SetMarketingPatternsGUI extends AbstractGUI {

	private JFrame frmCcrmSMP;
	private int pannelOpened=1; //1-first panel   2- second panel    3-third panel
	private ArrayList arr;
	private ArrayList<Area> arealist=null;
	private JComboBox typeList;
	private JComboBox productList;
	private JComboBox categoryList;
	private ArrayList<CheckBoxObject> areasList;;
	private CheckBoxJList areaCheckboxList;
	
	
	public SetMarketingPatternsGUI() {
		initialize();
		initGUI(frmCcrmSMP);
		frmCcrmSMP.getContentPane().setLayout(null);
		
		areasList = new ArrayList<CheckBoxObject>(); // initialize areaList arraylist 
		
		
		JButton btnNext = new JButton("Next");
		JButton btnFinish = new JButton("Finish");
		btnFinish.setVisible(false);
		
		// setting market segment panel
		Panel marketSegmentPanel = new Panel();
		marketSegmentPanel.setBackground(SystemColor.activeCaptionBorder);
		marketSegmentPanel.setBounds(38, 49, 346, 378);
		frmCcrmSMP.getContentPane().add(marketSegmentPanel);
		marketSegmentPanel.setLayout(null);
		marketSegmentPanel.setVisible(false);
		
		JLabel lblMarketSegmentPanell = new JLabel("Market Segment Panel");
		lblMarketSegmentPanell.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 12));
		lblMarketSegmentPanell.setBounds(98, 0, 149, 26);
		marketSegmentPanel.add(lblMarketSegmentPanell);
		
		JLabel lblNewLabel = new JLabel("Age Range:");
		lblNewLabel.setBounds(10, 53, 78, 26);
		marketSegmentPanel.add(lblNewLabel);
		
		JLabel lblFrom = new JLabel("");
		lblFrom.setBounds(98, 53, 40, 26);
		marketSegmentPanel.add(lblFrom);
		
		JLabel lblTo = new JLabel("---");
		lblTo.setBounds(181, 53, 28, 26);
		marketSegmentPanel.add(lblTo);
		
		JLabel lblArea = new JLabel("Area:");
		lblArea.setBounds(10, 96, 59, 26);
		marketSegmentPanel.add(lblArea);
		
		JLabel lblCustomerImportance = new JLabel("Customer Importance:");
		lblCustomerImportance.setBounds(10, 230, 138, 26);
		marketSegmentPanel.add(lblCustomerImportance);
		
		JLabel lblInterest = new JLabel("Interest level:");
		lblInterest.setBounds(10, 267, 108, 26);
		marketSegmentPanel.add(lblInterest);
		
		JLabel lblMarketingAcess = new JLabel("Marketing Access:");
		lblMarketingAcess.setBounds(10, 304, 108, 26);
		marketSegmentPanel.add(lblMarketingAcess);
		
		JCheckBox chckbxEnableAccess = new JCheckBox("enable access");
		chckbxEnableAccess.setBounds(141, 304, 121, 26);
		marketSegmentPanel.add(chckbxEnableAccess);
		
		JComboBox importanceCombo = new JComboBox();
		importanceCombo.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}));
		importanceCombo.setBounds(158, 233, 48, 20);
		marketSegmentPanel.add(importanceCombo);
		
		JComboBox interestCombo = new JComboBox();
		interestCombo.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}));
		interestCombo.setBounds(158, 270, 48, 20);
		marketSegmentPanel.add(interestCombo);
		
		JComboBox fromAgeCombo = new JComboBox();
		fromAgeCombo.setModel(new DefaultComboBoxModel(new String[] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101"}));
		fromAgeCombo.setBounds(108, 56, 48, 20);
		marketSegmentPanel.add(fromAgeCombo);
		
		JComboBox toAgeCombo = new JComboBox();
		toAgeCombo.setModel(new DefaultComboBoxModel(new String[] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101"}));
		toAgeCombo.setBounds(219, 56, 48, 20);
		marketSegmentPanel.add(toAgeCombo);
		
		
		// ----------------------------------- area list-------------------------------------------

		MaintainingResidentialAreaController.getAreas();
		
		areaCheckboxList = new CheckBoxJList(areasList);
		DefaultListModel defModel = new DefaultListModel();
		areaCheckboxList.setModel (defModel);
	    
		    for (int i=0;i<areasList.size();i++)
	        defModel.addElement (areasList.get(i).getName());

		    
	    JScrollPane scroller =
	        new JScrollPane (areaCheckboxList,
	                        ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
	                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
	 
		scroller.setBounds(108, 100, 190, 119);
		marketSegmentPanel.add(scroller);
		
		JButton RefreshBtn = new JButton("Refresh");
		RefreshBtn.addActionListener(new ActionListener() {
			@SuppressWarnings("unchecked")
			public void actionPerformed(ActionEvent arg0) {
				MaintainingResidentialAreaController.getAreas();
				defModel.removeAllElements();
			    for (int i=0;i<areasList.size();i++)
			        defModel.addElement (areasList.get(i).getName());
			}
		});
		RefreshBtn.setBounds(9, 157, 79, 26);
		RefreshBtn.setVisible(false);
		marketSegmentPanel.add(RefreshBtn);
		
		 //-------------------------------end of area list-------------------------------------
		
		
		
		// setting define product panel
		Panel defineProductPanel = new Panel();
		defineProductPanel.setBackground(SystemColor.activeCaptionBorder);
		defineProductPanel.setBounds(38, 49, 346, 341);
		frmCcrmSMP.getContentPane().add(defineProductPanel);
		defineProductPanel.setLayout(null);
		defineProductPanel.setVisible(true);
		
		
		typeList = new JComboBox();
		typeList.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if(categoryList.getSelectedIndex()!=-1){
            	if (typeList.getSelectedIndex()!=-1 || typeList.getSelectedIndex()!=-1)
        		getDistinctProducts(typeList.getSelectedItem().toString(), categoryList.getSelectedItem().toString());
            	else
                	{
                		getDistinctProducts("all",categoryList.getSelectedItem().toString());
                		typeList.setSelectedIndex(0);
                	}
			}
			}	
		});
//		typeList.addItemListener(new ItemListener() {
//			public void itemStateChanged(ItemEvent e) {
//            	if (categoryList.getSelectedIndex()!=-1 && typeList.getSelectedIndex()!=-1)
//        		getDistinctProducts(typeList.getSelectedItem().toString(), categoryList.getSelectedItem().toString());
//        	else
//        	{
//        		getDistinctProducts(typeList.getSelectedItem().toString(), "all");
//        		categoryList.setSelectedIndex(0);
//        	}
//			}
//		});
		typeList.setBounds(10, 132, 320, 26);
		
		defineProductPanel.add(typeList);
		
				
				
				
				productList = new JComboBox();
				productList.setBounds(10, 202, 320, 26);
//				productList.addListSelectionListener(new ListSelectionListener() {
//
//            @Override
//            public void valueChanged(ListSelectionEvent arg0) {
//                if (!arg0.getValueIsAdjusting()) {
//                	
//                	
//                  
//                }
//            }
//        });
				
				defineProductPanel.add(productList);
				
						
						categoryList = new JComboBox();
						categoryList.addItemListener(new ItemListener() {
							public void itemStateChanged(ItemEvent arg0) {
			                	if (typeList.getSelectedIndex()!=-1)
		                		getDistinctProducts(typeList.getSelectedItem().toString(), categoryList.getSelectedItem().toString());
			                	else
			                    	{
			                    		getDistinctProducts("all",categoryList.getSelectedItem().toString());
			                    		typeList.setSelectedIndex(0);
			                    	}
							}
						});
						categoryList.setBounds(10, 58, 320, 26);		
						
						defineProductPanel.add(categoryList);
						
						
						JLabel lblSelectCategory = new JLabel("Select Category");
						lblSelectCategory.setBounds(130, 26, 93, 26);
						defineProductPanel.add(lblSelectCategory);
						
						JLabel lblSelectType = new JLabel("Select Type");
						lblSelectType.setBounds(130, 100, 93, 26);
						defineProductPanel.add(lblSelectType);
						
						JLabel lblSelectProduct = new JLabel("Select Product");
						lblSelectProduct.setBounds(130, 170, 93, 26);
						defineProductPanel.add(lblSelectProduct);
						
						JLabel lblDefineProductPanel = new JLabel("Define Product Panel");
						lblDefineProductPanel.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 12));
						lblDefineProductPanel.setBounds(96, 0, 149, 26);
						defineProductPanel.add(lblDefineProductPanel);
						
						JButton RefreshListsBtn = new JButton("Refresh");
						RefreshListsBtn.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent e) {
								ManageTypesController.getProductTypes(); //fill types list
								SetMarketingPattersController.getProducts();//fill products list
								SetMarketingPattersController.getCategory(); // fill category list
								
							}
						});
						RefreshListsBtn.setBounds(130, 300, 84, 23);
						RefreshListsBtn.setVisible(true);
						defineProductPanel.add(RefreshListsBtn);
						
						
		

		ManageTypesController.getProductTypes(); //fill types list
		
		

		SetMarketingPattersController.getProducts();//fill products list
		SetMarketingPattersController.getCategory(); // fill category list
		
		/*
		// initial selected list items
		productList.setSelectedIndex(0);
		categoryList.setSelectedIndex(0);
		typeList.setSelectedIndex(0);
		*/
		
		
		Panel messageToClient = new Panel();
		messageToClient.setBackground(SystemColor.activeCaptionBorder);
		messageToClient.setBounds(38, 49, 346, 341);
		frmCcrmSMP.getContentPane().add(messageToClient);
		messageToClient.setLayout(null);
		messageToClient.setVisible(false);
		
		JLabel lblMessageToClient = new JLabel("Message To Client Panel");
		lblMessageToClient.setBounds(87, 0, 173, 15);
		lblMessageToClient.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 12));
		messageToClient.add(lblMessageToClient);
		
		JTextPane messageToClientPane = new JTextPane();
		messageToClientPane.setBounds(40, 61, 262, 218);
		messageToClient.add(messageToClientPane);
		
		JButton btnPrev = new JButton("Prev");
		btnPrev.setEnabled(false);
		btnPrev.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (pannelOpened==3)
				{
					pannelOpened=2;
					RefreshListsBtn.setVisible(false);
					RefreshBtn.setVisible(true);
					btnNext.setVisible(true);
					btnFinish.setVisible(false);
					messageToClient.setVisible(false);
					marketSegmentPanel.setVisible(true);
					defineProductPanel.setVisible(false);
					
				}
				else if (pannelOpened==2)
				{
					pannelOpened=1;
					RefreshListsBtn.setVisible(true);
					RefreshBtn.setVisible(false);
					btnPrev.setEnabled(false);
					messageToClient.setVisible(false);
					marketSegmentPanel.setVisible(false);
					defineProductPanel.setVisible(true);
					
				}
				
					
				
				
			}
		});
		
		
		btnPrev.setBounds(102, 443, 63, 23);
		frmCcrmSMP.getContentPane().add(btnPrev);
		
		
		btnNext.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				boolean areaSelectedCounter=false;
				
				
				if (pannelOpened==1)
				{
					if (productList.getSelectedIndex()==-1)
					{
						JOptionPane.showMessageDialog(frmCcrmSMP, "please select a product", "Define product panel", JOptionPane.ERROR_MESSAGE);
					}
					else
					{
					pannelOpened=2;
					RefreshBtn.setVisible(true);
					RefreshListsBtn.setVisible(false);
					btnPrev.setEnabled(true);
					messageToClient.setVisible(false);
					marketSegmentPanel.setVisible(true);
					defineProductPanel.setVisible(false);
					}
					
				}
				else if (pannelOpened==2)
				{
					RefreshBtn.setVisible(false);
					RefreshListsBtn.setVisible(false);
					for (int i=0;i<areaCheckboxList.objs.size();i++)
						if (areaCheckboxList.objs.get(i).getSlected()==1)
							areaSelectedCounter=true;
							
					
					if (!areaSelectedCounter)
					{
						JOptionPane.showMessageDialog(frmCcrmSMP, "please select atleast one area", "Market Segment panel", JOptionPane.ERROR_MESSAGE);
						
					
					}
					else if (Integer.parseInt(fromAgeCombo.getSelectedItem().toString())==Integer.parseInt(toAgeCombo.getSelectedItem().toString()))
					{
						JOptionPane.showMessageDialog(frmCcrmSMP, "age range cant consist identical numbers", "Market Segment panel", JOptionPane.ERROR_MESSAGE);
					}
					else
					{
						pannelOpened=3;
						btnNext.setVisible(false);
						btnFinish.setVisible(true);
						messageToClient.setVisible(true);
						marketSegmentPanel.setVisible(false);
						defineProductPanel.setVisible(false);
					}
						
						
						
					
					
					
				}
				
			}
		});
		btnNext.setBounds(248, 443, 63, 23);
		frmCcrmSMP.getContentPane().add(btnNext);
		
		JLabel lblSetMarketingPatterns = new JLabel("Set Marketing Patterns");
		lblSetMarketingPatterns.setBounds(136, 11, 163, 29);
		frmCcrmSMP.getContentPane().add(lblSetMarketingPatterns);
		
		
		btnFinish.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String product = productList.getSelectedItem().toString();
				int productID=Integer.parseInt(product.substring(1,product.indexOf(" ")));
				String areasStr = "";
				for (int i=0;i<areaCheckboxList.objs.size();i++)
					if (areaCheckboxList.objs.get(i).getSlected()==1)
						areasStr+=areaCheckboxList.objs.get(i).getName() + ";";
				int accessChecked=0;
				if (chckbxEnableAccess.isSelected())
					accessChecked=1;
				else
					accessChecked=0;
				
				
				SetMarketingPattersController.setMarketingPattern(productID,fromAgeCombo.getSelectedIndex(),toAgeCombo.getSelectedIndex(),areasStr,importanceCombo.getSelectedIndex()+1,interestCombo.getSelectedIndex()+1,accessChecked,messageToClientPane.getText());
			}
		});
		btnFinish.setBounds(221, 433, 117, 42);
		frmCcrmSMP.getContentPane().add(btnFinish);
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmCcrmSMP = new JFrame();
		frmCcrmSMP.setResizable(false);
		frmCcrmSMP.setTitle("CCRM>Set Marketing Patterns");
		frmCcrmSMP.setBounds(100, 100, 435, 517);
		frmCcrmSMP.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frmCcrmSMP.setVisible(true);
		

	}
	
	public void getDistinctProducts(String typ,String cat)
	{
		int type,category;
		int indexOfSpace;
		
		if (typ.equals("all")|| typ==null)
			type=-1;

		else
			type=Integer.parseInt(typ.substring(1,typ.indexOf(" ")));
		
		
		
		if (cat.equals("all")||cat==null)
			category=-1;
		
		else
			
			category=Integer.parseInt(cat.substring(1,cat.indexOf(" ")));
		
		SetMarketingPattersController.getProducts(type,category);
		
	}
	
	public void getDistinctTypes(String cat)
	{
		int category;
		
			category=Integer.parseInt(cat.substring(1,cat.indexOf(" ")));

			SetMarketingPattersController.getType(category);
		
	}
	

	@SuppressWarnings("unchecked")
	@Override
	public void getReply(Object r) {
		if(((Reply)r).command.equals(Command.GET_PRODUCTS)) //if GET_PRODUCTS reply is received
		{
			arr =(ArrayList<Product>) ((Reply)r).result;
			//productList.removeAll();
			if(productList.getItemCount()>0)
			productList.removeAllItems();
			
			for(int i=0;i<arr.size();i++)

				productList.addItem(arr.get(i).toString());

			
			

		}
		else if(((Reply)r).command.equals(Command.GET_PRODUCT_TYPES_BY_CATEGORY)) //if GET_PRODUCTS reply is received
		{
			arr =(ArrayList<Type>) ((Reply)r).result;
			typeList.removeAllItems();
			if(!areasList.isEmpty())
			for(int i=0;i<arealist.size();i++)
				typeList.addItem(arr.get(i).toString());
		}
		
		else if(((Reply)r).command.equals(Command.GET_AREAS)) //if GET_PRODUCTS reply is received
		{
			arealist =(ArrayList<Area>) ((Reply)r).result;
			if(!areasList.isEmpty())
			areasList = new ArrayList<CheckBoxObject>();
			for(int i=0;i<arealist.size();i++)
				areasList.add(new CheckBoxObject(arealist.get(i).getAreaName(), 0));
		}
		else if(((Reply)r).command.equals(Command.GET_PRODUCT_CATEGORIES)) //if GET_PRODUCTS reply is received
		{
			arr =(ArrayList<Category>) ((Reply)r).result;
			//categoryList.removeAll();
			if(categoryList.getItemCount()>0)
			categoryList.removeAllItems();
			categoryList.addItem("all");
			categoryList.setSelectedIndex(0);
			
			
			for(int i=0;i<arr.size();i++)
			
				categoryList.addItem(arr.get(i).toString());
			
			
		}
		else if(((Reply)r).command.equals(Command.GET_PRODUCT_TYPES)) //if GET_PRODUCTS reply is received
		{
			arr =(ArrayList<Type>) ((Reply)r).result;
			//typeList.removeAll();
			if(typeList.getItemCount()>0)
			typeList.removeAllItems();
			typeList.addItem("all");
			typeList.setSelectedIndex(0);
			
			
			for(int i=0;i<arr.size();i++)
			{
				typeList.addItem(arr.get(i).toString());
			}
			
			
		
			
		}
		else if(((Reply)r).command.equals(Command.ADD_MARKETING_PATTERN)) //if GET_PRODUCTS reply is received
		{
			Result result= (Result) ((Reply)r).result;
			if(result.equals(Result.OK))
			{
				System.out.println(result.toString());
				JOptionPane.showMessageDialog(frmCcrmSMP, "NEW Marketing Pattern Created!", "CCRM>Set Marketing Pattern", JOptionPane.INFORMATION_MESSAGE);
				this.goBack();
			
			}
			
			else if(result.equals(Result.FAILED))
			{
				System.out.println("Unable to add the pattern");
				JOptionPane.showMessageDialog(frmCcrmSMP, "Unable to create a marketing pattern!", "CCRM>Set Marketing Pattern", JOptionPane.ERROR_MESSAGE);
			}
			
		
			
		}
		
	}
}
